//
//  FileExplorer.ViewModel.swift
//  SwiftCode
//
//  Created by 于虎拴 on 2023/4/11.
//

import Foundation
import RxSwift
import RxCocoa

extension FileExplorer {
  final class ViewModel {
    let bag = DisposeBag()
    
    struct Input {
      let lessThanOnTapped: ControlEvent<Void>
      let greaterThanOnTapped: ControlEvent<Void>
      let keyFilter: Observable<String>
      let rootPath: String
      let itemSelected: ControlEvent<IndexPath>
      let viewController: UIViewController
    }
    
    struct Output {
      let pathsValue: Observable<[String]>
      let toastValue: Observable<String>
    }
    
    func adapt(input: Input) -> Output {
      let toastSubject = PublishSubject<String>()
      
      let rootURL = URL(fileURLWithPath: input.rootPath)
      let filenames: [String]
      if rootURL.hasDirectoryPath {
        let temp = try? FileManager.default.contentsOfDirectory(atPath: rootURL.path)
        filenames = temp ?? []
      } else {
        filenames = [rootURL.lastPathComponent]
      }
      
      let pathsSubject = BehaviorSubject<[String]>(value: filenames)
      
      // 升序
      input.lessThanOnTapped
        .map { filenames.sorted() }
        .bind(to: pathsSubject)
        .disposed(by: bag)
      
      // 降序
      input.greaterThanOnTapped
        .map { filenames.sorted(by: >) }
        .bind(to: pathsSubject)
        .disposed(by: bag)
      
      // 关键字过滤
      input.keyFilter
        .map { key in
          if key.isEmpty { return filenames }
          return filenames.filter { $0.contains(key) }
        }
        .bind(to: pathsSubject)
        .disposed(by: bag)
      
      // item 点击
      input.itemSelected
        .asObservable()
        .withLatestFrom(pathsSubject) { ($0, $1[$0.row]) }
        .subscribe(onNext: { [weak viewController = input.viewController] indexPath, filename in
          guard let viewController = viewController else { return }
          let fileURL = URL(fileURLWithPath: input.rootPath).appendingPathComponent(filename)
          
          if fileURL.hasDirectoryPath {
            viewController.navigationController?.pushViewController(ViewController(fileURL.absoluteString), animated: true)
          } else {
            toastSubject.onNext("处理打开...")
          }
        })
        .disposed(by: bag)
      
      return .init(pathsValue: .empty(), toastValue: toastSubject)
    }
  }
}
